package com.config.security;

import com.entity.sys.Menu;
import com.entity.sys.Role;
import com.service.sys.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 权限控制 根据请求url分析请求所需要的一个角色
 *
 * @author Clay
 */
@Slf4j
@Component
public class CustomerFilter implements FilterInvocationSecurityMetadataSource {

    @Resource
    private MenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<Menu> menuWithRole = menuService.getMenuWithRole();
        log.info("校验访问url==> requestUrl : {}", requestUrl);
        List<String> roleNames = new ArrayList();
        for (Menu menu : menuWithRole) {
            //判断url与菜单角色所需要的url是否一致 主要匹配前缀, 比如
            //统计处所有匹配的权限
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                for (String s : str) {
                    roleNames.add(s);
                }
            }
        }
        if (roleNames.size() == 0) {
            //没匹配的url默认登录即可访问
            return org.springframework.security.access.SecurityConfig.createList("ROLE_LOGIN");
        }
        String[] objects = roleNames.toArray(new String[roleNames.size()]);
        return org.springframework.security.access.SecurityConfig.createList(objects);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
